/**
 * @description: 「主持风采」模块store
 * @author: Ruan Jiazhen
 * @date: 2024-03-08 09:47:38
 **/
import { reqGetProfile, reqGetWorkList } from '@/api/hosting-style';
import { observable, action } from 'mobx-miniprogram';

export const hostingStyleStore = observable({
  /** 主持人资料 */
  profile: {
    /** 是否已经获取过资料 */
    isGetProfile: false,
    consult_num: 0,
    host_style_phone: '',
    host_style_sign: '',
    host_num: 0,
    user_province: '',
    user_city: '',
    user_desc: '',
    user_headimg: '',
    user_lbt: '',
    user_qm_name: '',
    user_sex: '',
    user_wx: '',
    wx_qr_code: '',
    tagList: [],
    backgroundUrl: '',
    isDefaultBg: false,
  } as HostingStyleProfile,

  getProfile: action(async function () {
    try {
      const res = await reqGetProfile();
      if (res?.code === 200) {
        const bgInfo = JSON.parse(res.data.user_lbt || '[]')[0];
        this.profile = {
          ...this.profile,
          isGetProfile: true,
          ...res.data,
          tagList: res.data.host_style_sign ? res.data.host_style_sign?.split(',') : [],
          backgroundUrl: bgInfo.mediaPath,
          isDefaultBg: bgInfo.isDefaultBg,
        };
      }
    } catch (e: any) {
      wx.showToast({ title: e.message, icon: 'error' });
    }
  }),

  /** 作品列表 */
  workList: [] as Work[],

  /** 获取作品列表分页参数 */
  workListPagination: {
    page: 1,
    pageSize: 10,
    total: -1,
  },

  /** 获取作品列表 */
  getWorkList: action(async function () {
    if (this.workListPagination.total !== -1 && this.workList.length >= this.workListPagination.total) {
      wx.showToast({ title: '没有更多了', icon: 'none' });
      return;
    }
    try {
      const res = await reqGetWorkList(this.workListPagination.page, this.workListPagination.pageSize);
      if (res?.code === 200) {
        this.workList = this.workList.concat(
          res.data.list.map((item) => {
            return {
              ...item,
              cover: item?.cover || JSON.parse(item.imageList)[0] || item.video + '?vframe/jpg/offset/1',
              parsedImageList: JSON.parse(item.imageList),
            } as Work;
          }),
        );
        this.workListPagination.total = res.data.totalResult;
        this.workListPagination.page += 1;
      }
    } catch (e: any) {
      wx.showToast({ title: e.message, icon: 'error' });
    }
  }),

  /** 重置作品列表 */
  resetWorkList: action(function () {
    this.workList = [];
    this.workListPagination = {
      page: 1,
      pageSize: 10,
      total: -1,
    };
  }),

  /** 更新作品点赞状态 */
  updateWorkLikeStatus: action(function (workId: number, isLike = true) {
    this.workList = this.workList.map((item: Work) => {
      if (item.find_id === workId) {
        item.isLike = isLike;
        item.likes += isLike ? 1 : -1;
      }
      return item;
    });
  }),

  /** 删除作品 */
  deleteWork: action(function (workId: number) {
    this.workList = this.workList.filter((item: Work) => item.find_id !== workId);
  }),
});
